<template>
    <div>
        <div class="main-question-list">
            <div style="padding: 0; display: inline">
                <el-card style="position: relative">
                    <div class="box-is-not-selected-wrapper" @click="editTitle">
                        <div v-if="questionnaire.isBoxSelected===false" :class="[!isSaveTitle ? 'box-is-not-selected' : '']">
                            <h1>{{questionnaire.questionnaireTitle}}</h1>
                            <h3>{{questionnaire.formulaId}}</h3>
                        </div>

                        <div v-show="!isSaveTitle" class="edit-icon"><i class="el-icon-edit-outline"></i></div>
                    </div>
                    <div v-if="questionnaire.isBoxSelected===true">
                        <el-form>
                            <el-form-item>
                                <el-input
                                        style="max-width: 50%"
                                        placeholder="请输入问卷标题"
                                        v-model="questionnaire.questionnaireTitle"
                                ></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-select 
                                    v-model="questionnaire.formulaId"
                                    style="max-width: 50%"
                                    placeholder="请选择公式" 
                                    @change="changeRule"
                                >
                                    <el-option v-for="item in questRuleOptions" :key="item.value" :label="item.label" :value="item.value" />
                                    </el-select>
                            </el-form-item>

                            <el-form-item>
                                <el-button type="primary" @click="saveQuestionnaireTitle">保存</el-button>
                                <el-button @click="resetQuestionnaireTitle">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>
            </div>
            <div style="height: 10px"></div>


            <Question v-for="(item,index) in questionList"
                      :key="index"
                      :is-box-selected="item.isBoxSelected"
                      :question-index="index"
                      :question-title="item.questionTitle"
                      :question-nullable="item.questionNullable"
                      :question-description="item.questionDescription"
                      :parameterVal = "item.parameterVal"
                      :parameterData="item.parameterData"
                      :question-type="item.questionType"
                      :front-choose="item.frontChoose"
                      :front-options-init-value="item.frontOptions"
                      :front-options="frontOptions(index)"
                      :date="item.date"
                      :default-number="item.defaultNumber"
                      :grade-max="item.gradeMax"
                      :number-type="item.numberType"
                      :question-options="item.questionOptions"
                      :text-description="item.textDescription"
                      @clickUnSelected="selectOneBox(index)"
                      @clickSelected="selectOneBox(index)"
                      @saveOneQuestion="saveOneQuestion"
                      @resetQuestion="resetQuestion(index)"
                      @clickDelete="deleteOneBox(index)"
            ></Question>
            <el-card class="add-question" :body-style="{ padding: '10px' }" shadow="hover">
                <div class="add-question-inner" @click="addNewQuestion('not_selected')"><i class="el-icon-plus"></i>
                    添加问题
                </div>
            </el-card>
            <el-card>

                <el-dialog
                        width="30%"
                        title="确认删除？"
                        v-model="deleteVisible"
                        append-to-body
                        center
                >
                <span slot="footer" class="dialog-footer">
                    <el-button @click="deleteVisible=false">取 消</el-button>
                    <el-button @click="deleteQuestionnaire" type="danger">确认删除</el-button>
                </span>

                </el-dialog>
                <el-dialog
                        width="30%"
                        title="发布成功"
                        v-model="releaseVisible"
                        append-to-body
                        center
                >
                    <div>问卷链接为：
                        <el-link class="copy-link"
                                target="_blank" @click="copy"
                                :data-clipboard-text="servername+'/fillin/'+route.params.id"
                                data-clipboard-action="copy"
                                type="primary"
                        >
                            {{questionnaire.questionnaireTitle}}-点击复制
                        </el-link>
                    </div>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="releaseEnd" type="primary">关 闭</el-button>
                    </span>

                </el-dialog>

                <el-button type="danger" @click="deleteVisible = true">删 除</el-button>
                <el-button @click="saveQuestionnaire">保 存</el-button>
                <el-button @click="releaseQuestionnaire" type="primary">发 布</el-button>
            </el-card>


        </div>
    </div>
</template>

<script setup name="MainQuestionList">
import { ElMessage } from 'element-plus';
import Question from "./Question";
import Clipboard from 'clipboard';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router'
import { ruleQuery, formulaData } from '@/api/safeguard/index.js';
const route = useRoute();
const router = useRouter();

const questionList = ref([]);
const questionnaire = ref({
    isBoxSelected: false,
    questionnaireDescription: "请输入描述",
    questionnaireTitle: "请输入标题",
    formulaId: '',
    questionnaireId: route.params.id,
});
const isSaveTitle = ref(false)
const questMaxLimit = ref(0)
const deleted = ref(false);
const deleteVisible = ref(false);
const releaseVisible = ref(false);
const questRuleOptions = ref([])
const servername = window.origin

const newQuestion = ref({
    questionIndex: questionList.value.length,
    isBoxSelected: true,
    questionTitle: "",
    questionNullable: false,
    questionDescription: "",
    parameterVal: '',
    parameterData: [],
    questionType: 'not_selected',
    questionOptions: [''],
    frontOptions: [[]],
    frontChoose: false,
    numberType: 'integer',
    defaultNumber: 0,
    gradeMax: 5,
    date: new Date(),
    textDescription: '',
});

if(route.params.id){
    fetchData();
}

function getList () {
  ruleQuery('123').then(res => {
    res.data.length > 0 && res.data.map(item => {
        questRuleOptions.value.push({
            value: item.formulaId,
            label: item.formulaId + '-' + item.formulaCode
        })
    })
  })
}
getList()

function getformulaData(val) {
    formulaData(val).then(res => {
        questMaxLimit.value = res.data.length
        const list = []
        res.data.length> 0 && res.data.map(item => {
            list.push({
                value: item.code,
                label: item.txt,
                valueType: item.valueType
            })
        })
        newQuestion.value.parameterData = list
    }) 
}
function changeRule (e) {
    getformulaData(e)
}
function fetchData() {
    axios.get("/adviser/getQuestionList", {
        params: {
            questionnaireId: route.params.id,
        }
    }).then((res) => {
        const tempList = res.data['questionList'];
        const resList = [];
        for (const t of tempList) {
            t['date'] = new Date(t['date']);
            resList.push(t);
        }
        questionList.value = resList;
        ElMessage({message: "问卷已读取", duration: 1000});
    }).catch(() => {
        ElMessage({message: "问卷读取失败！", duration: 1000});
    })

    axios.get("/adviser/getQuestionnaireOutline", {
        params: {
            questionnaireId: route.params.id
        }
    }).then((res) => {
        const temp = {
            isBoxSelected: false,
            questionnaireDescription: res.data['questionnaire']['description'],
            formulaId: res.data['questionnaire']['formulaId'],
            questionnaireTitle: res.data['questionnaire']['title'],
            questionnaireId: res.data['questionnaire']['questionnaireId'],
        };
        questionnaire.value = temp;
        getformulaData(temp.formulaId)
    }).catch(() => {
        ElMessage({message: "问卷概况读取失败！", duration: 1000})
    })
}

function selectOneBox(index) {
    questionList.value[index].isBoxSelected = !questionList.value[index].isBoxSelected;
}

function resetQuestion(index) {
    return;  // process in the question.vue
}

function saveOneQuestion(data) {
    const index = data['questionIndex'];
    const oneQuestion = {
        questionIndex: index,
        isBoxSelected: true,
        questionTitle: data['questionTitle'],
        questionNullable: data['questionNullable'],
        questionDescription: data['questionDescription'],
        parameterCode: data['parameterCode'],
        questionType: data['questionType'],
        questionOptions: data['questionOptions'],
        frontOptions: data['frontOptions'],
        frontChoose: data['frontChoose'],
        numberType: data['numberType'],
        defaultNumber: data['defaultNumber'],
        gradeMax: data['gradeMax'],
        date: data['date'],
        textDescription: data['textDescription'],
    };
    newQuestion.value.parameterData = newQuestion.value.parameterData.filter(item => item.value !== oneQuestion.parameterCode)
    questionList.value.splice(index, 1, oneQuestion);
    axios.post("/adviser/saveOneQuestion?questionnaireId=" + route.params.id, {
        question: oneQuestion,
    }).then(() => {
        ElMessage({message: "问卷已保存", type: 'success',  duration: 1000});
    }).catch(() => {
        ElMessage({message: "问卷未保存！", type: 'error', duration: 1000});
    });
}

function deleteOneBox(index) {
    questionList.value.splice(index, 1);
}

function addNewQuestion(type) {
    if(questionList.value.length >= questMaxLimit.value ) {
        ElMessage({message: "该公式问卷最多添加" + questMaxLimit.value + "个问题",  duration: 1000});
        return
    }
    
    questionList.value.push(newQuestion.value);
    console.log('add===', questionList.value)
}
function saveQuestionnaireTitle() {
    if(!questionnaire.value.formulaId) {
        ElMessage({message: "请选择公式"});
        return
    }
    questionnaire.value.isBoxSelected = false;
    axios.post("/adviser/saveQuestionnaireOutline", {
        questionnaire: questionnaire.value,
    }).then((response) => {
        console.log('saveQuestionnaireOutline',response);
        questionnaire.value.questionnaireId = response.data;
        route.params.id = response.data;
        isSaveTitle.value = true
        ElMessage({message: "问卷已保存", type: 'success', duration: 1000});
    }).catch(() => {
        ElMessage({message: "问卷未保存！", type: 'error', duration: 1000});
    });
}
function resetQuestionnaireTitle() {
    questionnaire.value = {
        isBoxSelected: false,
        questionnaireDescription: "请输入描述",
        formulaId: '',
        questionnaireTitle: "请输入标题",
        questionnaireId: route.params.id,
    };
}
function editTitle() {
    if(isSaveTitle.value) return
    questionnaire.value.isBoxSelected = true;
}
function saveQuestionnaire() {
    axios.post("/adviser/saveQuestionnaire", {
        questionnaire: questionnaire.value,
        questionList: questionList.value,
    }).then(() => {
        ElMessage({message: "问卷已保存", type: 'success', duration: 1000});
    }).catch(() => {
        ElMessage({message: "问卷未保存！", type: 'error', duration: 1000});
    });
    console.log(router, route, 'router.history.back()')
    router.back(0)
}
function deleteQuestionnaire() {
    deleteVisible.value = false;
    axios.get('/adviser/deleteQuestionnaire', {params: {questionnaireId: questionnaire.value.questionnaireId}}).then((response) => {
        console.log(response);
        router.back();
        deleted.value = true;
        ElMessage({message: "问卷已删除", type: 'success', duration: 1000});
    })
}
function frontOptions (index) {
    const res = [];

    for (let i = 0; i < index; i++) {
        const temp = questionList.value[i];
        if (temp != null) {
            const oneQuestion = {
                label: temp['questionTitle'],
                value: index,
                children: temp['questionOptions'].map((item) => {
                    return {value: item, label: item}
                })
            }
            res.push(oneQuestion);
        }
    }
    return res;
}
function releaseQuestionnaire() {
    axios.post("/adviser/releaseQuestionnaire?questionnaireId=" + route.params.id)
        .then(() => {
            ElMessage({message: "问卷已发布", type: 'success', duration: 1000});
        }).catch(() => {
            ElMessage({message: "error！问卷未发布！", type: 'error', duration: 1000});
        });
        console.log(releaseVisible.value, '======')
    releaseVisible.value = true;
}
function releaseEnd() {
    releaseVisible.value = false;
    router.back();
}
function copy() {
    const clipboard = new Clipboard('.copy-link')
    clipboard.on('success', e => {
        console.log('复制成功')
        ElMessage({message: "复制成功", type: 'success', duration: 1000})
        // 释放内存
        clipboard.destroy()
    })
    clipboard.on('error', e => {
        // 不支持复制
        console.log('该浏览器不支持自动复制')
        // 释放内存
        clipboard.destroy()
    })
}
defineExpose({
    addNewQuestion,
});
</script>

<style scoped>
    .main-question-list {
        height: 100%;
        background-color: white;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .add-question-inner {
        width: 50%;
        height: 50px;
        line-height: 50px;
        /* padding-top: 25px; */
        text-align: center;
        margin-left: auto;
        margin-right: auto;
        border-color: rgba(128, 128, 128, 0.5);
        color: rgba(128, 128, 128, 0.5);
        border-width: 2px;
        border-style: dashed;
        font-weight: bolder;
        cursor: pointer;
    }

    .box-is-not-selected {
        position: relative;
    }

    .box-is-not-selected-wrapper {
        cursor: pointer;
    }

    .box-is-not-selected-wrapper:hover .box-is-not-selected {
        filter: blur(8px);
    }

    .edit-icon {
        display: none;
    }

    .box-is-not-selected-wrapper:hover .edit-icon {
        display: inline;
        height: 100%;
        width: 100%;
        background-color: rgba(179, 229, 252, 0.3);
        position: absolute;
        top: 0;
        left: 0;
    }

    .el-icon-edit-outline {
        position: absolute;
        top: calc(50% - 30px);
        left: calc(50% - 30px);
        font-size: 60px;
        color: rgba(128, 0, 128, 0.6);
    }

</style>